﻿using Anke.SHManage.Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity;
using Anke.SHManage.Utility;
using Anke.SHManage.IDAL;

namespace Anke.SHManage.MSSQLDAL
{
    /// <summary>
    /// 获取任务数据
    /// </summary>
    public class MobileTaskDAL
    {
        private string m_TableName = "";//字典表名
        IDALContext dalContext = new DALContextFactory().GetDALContext();
        AKV7ManageEntities db = DBContextFactory.GetDBContext() as AKV7ManageEntities;

        #region 给移动终端用的任务数据
        /// <summary>
        ///  给移动终端用的任务数据 2015-12-04 
        /// </summary>
        /// <param name="personCode"></param>
        /// <returns></returns>
        public List<MobileTaskInfo> GetMobileTaskListBy(string userCode, string taskCode, ref string errorMsg)
        {
            try
            {
                SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(SqlHelper.MainConnectionString);//取管理库的链接字符串
                StringBuilder sbSQL = new StringBuilder();//sql语句
                sbSQL.Append("declare @taskCode char(22) ");
                sbSQL.Append("set @taskCode='" + taskCode + "' ");

                sbSQL.Append("declare @UserCode varchar(50) ");
                sbSQL.Append("set @UserCode=(select 编码 from TPerson where 工号='" + userCode + "') ");

                //2016-12-21 zch 备份
                    //tt.任务编码,
                    //            tt.用户流水号,
                    //            case when pr.LocalAddress is null then ate.现场地址 else pr.LocalAddress end as '现场地址',
                    //            tt.到达现场时刻,tt.生成任务时刻,tae.首次受理时刻,
                    //            tt.出车时刻,tt.到达现场时刻,tt.离开现场时刻,tt.到达医院时刻,
                    //            tt.完成时刻,tt.返回站中时刻,
                    //            case when pr.[Name] is null then ate.患者姓名 else pr.Name end as '患者姓名',
                    //            tae.事件类型编码,    
                    //            case when pr.PatientVersion is null then tzaet.名称  else pr.PatientVersion end as '事件类型',                               
                    //            司机=isnull(dbo.GetStr(tt.任务编码,3),''),                                
                    //            医生=isnull(dbo.GetStr(tt.任务编码,4),''),                              
                    //            护士=isnull(dbo.GetStr(tt.任务编码,5),''),
                    //            case when pr.OriginalTaskType is null then tzaet.名称  else pr.OriginalTaskType end as '原事件类型', 
                    //            case when pr.ContactTelephone is null then ate.联系电话  else pr.ContactTelephone end as '联系电话', 
                    //            case when pr.ForArea is null then tae.区域  else pr.ForArea end as '区域'

                //2016-12-21 zch 修改 取任务时多病历的情况下,只取不提交的,并且默认第一条病历的相关信息. distinct 任务
                string sqlStr = @"   select distinct  top 10
                            	tt.任务编码,
		                        tt.用户流水号,
	                        ate.现场地址 as '现场地址',
		                        tt.到达现场时刻,tt.生成任务时刻,tae.首次受理时刻,
		                        tt.出车时刻,tt.到达现场时刻,tt.离开现场时刻,tt.到达医院时刻,
		                        tt.完成时刻,tt.返回站中时刻,
		                         ate.患者姓名 as '患者姓名',ate.患者人数,
		                        tae.事件类型编码,    
		                        tzaet.名称  as '事件类型',                               
		                        司机=isnull(dbo.GetStr(tt.任务编码,3),''),                                
		                        医生=isnull(dbo.GetStr(tt.任务编码,4),''),                              
		                        护士=isnull(dbo.GetStr(tt.任务编码,5),''),
                                担架员=isnull(dbo.GetStr(tt.任务编码,6),''),
		                         tzaet.名称 as '原事件类型', 
		                         ate.联系电话  as '联系电话', 
	                         tae.区域  as '区域'
								--case when pr.[TaskCode] is null then '未填' else '已填' end as '状态',
                                --case when pc.[TaskCode] is null then '未收' else '已收' end as '收费' 
                                from TTask tt
                                LEFT JOIN TAcceptEvent ate on ate.事件编码= tt.事件编码 and ate.受理序号=tt.受理序号
                                LEFT JOIN TAlarmEvent tae on tae.事件编码= tt.事件编码
                                LEFT JOIN TZAlarmEventType tzaet on tae.事件类型编码 = tzaet.编码
                                LEFT JOIN dbo.TTaskPersonLink  tpl on tpl.任务编码=tt.任务编码 
            
                                 ";
                sbSQL.Append(sqlStr);
                sbSQL.Append(" left join ").Append(builder.InitialCatalog).Append(".dbo.M_PatientRecord  pr on pr.[TaskCode]=tt.任务编码");
                sbSQL.Append(" left join ").Append(builder.InitialCatalog).Append(".dbo.M_PatientCharge  pc on pc.[TaskCode]=tt.任务编码");
                sbSQL.Append(@" 
                               where ");

                string TaskCodeEnd = DateTime.Now.AddDays(-AppConfig.GetConfigInt("PADSelectTime")).ToString("yyyyMMddHHmmss") + "00000000";//PAD查询截止时间
                if (taskCode != "")
                {
                    sbSQL.Append(" tt.任务编码<@taskCode And");
                }

                //edit2024-09-18 plq 现场需求，加上 已提交病例但分组抽查未通过的任务数据
                if (AppConfig.GetConfigBool("IsPADLoadSubCenterSpotChecksFailed"))
                {
                    sbSQL.Append(@" (pr.SubmitLogo=0 or pr.SubmitLogo is null 
                                                     or pr.SubCenterSpotChecksResult='未通过') And ");//20151216去掉已经提交的病历
                }
                else
                {
                    sbSQL.Append(" (pr.SubmitLogo=0 or pr.SubmitLogo is null) And ");//20151216去掉已经提交的病历
                }
                sbSQL.Append(@" 
                              tt.任务编码>'" + TaskCodeEnd + "' AND ");//20151213查询截止时间
                sbSQL.Append(@" 
                              tpl.人员编码=@UserCode ");
                sbSQL.Append(@" 
                              order by tt.任务编码 desc");

                DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.AttemperConnectionString, CommandType.Text, sbSQL.ToString(), null);
                List<MobileTaskInfo> list = new List<MobileTaskInfo>();
                if (ds.Tables[0].Rows.Count > 0)
                {
                    foreach (DataRow dr in ds.Tables[0].Rows)
                    {
                        MobileTaskInfo info = new MobileTaskInfo();
                        info.RenWuBianMa = dr["任务编码"].ToString();
                        info.YongHuLiuShuiHao = dr["用户流水号"].ToString();
                        info.XianChangDiZhi = dr["现场地址"].ToString();
                        info.DaoDaXianChangShiKe = dr["生成任务时刻"].ToString();
                        info.HuanZheXingMing = dr["患者姓名"].ToString();
                        info.EventType = dr["事件类型编码"].ToString();
                        info.EventTypeName = dr["事件类型"].ToString();
                        info.SiJi = dr["司机"].ToString();
                        info.YiSheng = dr["医生"].ToString();
                        info.HuShi = dr["护士"].ToString();
                        info.DanJiaYuan = dr["担架员"].ToString();
                        //info.BingLi = dr["状态"].ToString();
                        //info.ShouFei = dr["收费"].ToString();
                        info.OriginalTaskType = dr["原事件类型"].ToString();//20151211
                        info.ForHelpTelephone = dr["联系电话"].ToString();//20151211
                        info.ForArea = dr["区域"].ToString();//20151211
                        //info.Blload = 1;
                        //info.Sfload = 1;
                        info.DrivingTime = dr["出车时刻"].ToString();//20151224
                        info.ArriveSceneTime = dr["到达现场时刻"].ToString();//20151224
                        info.LeaveSceneTime = dr["离开现场时刻"].ToString();//20151224
                        info.ArriveDestinationTime = dr["到达医院时刻"].ToString();//20151224
                        info.FirstAcceptTime = dr["首次受理时刻"].ToString();//20160107
                        info.PatientNum = Convert.ToInt32(dr["患者人数"]); //add2021-10-18 plq 医保上线移植
                        list.Add(info);
                    }
                }

                return list;
            }
            catch (Exception ex)
            {
                List<MobileTaskInfo> listError = null;
                errorMsg = "系统错误：" + ex.Message;
                return listError;
            }
        }
        /// <summary>
        ///  给移动终端用的任务数据
        /// </summary>
        /// <param name="personCode"></param>
        /// <returns></returns>
        public void GetMobileTaskInfo(string taskCode, out string HJTel, out string Area, out string EventType)
        {
            try
            {
                HJTel = "";
                Area = "";
                EventType = "";
                StringBuilder sbSQL = new StringBuilder();//sql语句
                sbSQL.Append("declare @taskCode char(22) ");
                sbSQL.Append("set @taskCode='" + taskCode + "' ");


                string sqlStr = @"   select   
                                tt.任务编码,tzaet.名称 as 事件类型 ,ate.联系电话,tae.区域                       from TTask tt
                                LEFT JOIN TAcceptEvent ate on ate.事件编码= tt.事件编码 and ate.受理序号=tt.受理序号
                                LEFT JOIN TAlarmEvent tae on tae.事件编码= tt.事件编码
                                LEFT JOIN TZAlarmEventType tzaet on tae.事件类型编码 = tzaet.编码                where tt.任务编码=@taskCode ";


                sbSQL.Append(sqlStr);
                DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.AttemperConnectionString, CommandType.Text, sbSQL.ToString(), null);

                if (ds.Tables[0].Rows.Count > 0)
                {
                    HJTel = ds.Tables[0].Rows[0]["联系电话"].ToString();
                    Area = ds.Tables[0].Rows[0]["区域"].ToString();
                    EventType = ds.Tables[0].Rows[0]["事件类型"].ToString();
                }


            }
            catch (Exception ex)
            {
                HJTel = "";
                Area = "";
                EventType = "";
            }
        }
        #endregion

        #region 根据时间、中心编码、用户流水号获取出车信息
        public List<MobileTaskInfo> GetMobileTaskListsBy(string begintime, string endtime, string centerCode, string taskOrder, ref string errorMsg)
        {
            try
            {
                SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(SqlHelper.MainConnectionString);//取管理库的链接字符串
                StringBuilder sbSQL = new StringBuilder();//sql语句
                //sbSQL.Append("declare @taskCode char(22) ");
                //sbSQL.Append("set @taskCode='" + taskCode + "' ");

                //sbSQL.Append("declare @UserCode varchar(50) ");
                //sbSQL.Append("set @UserCode=(select 编码 from TPerson where 工号='" + userCode + "') ");

                string sqlStr = @"   select top 20
                                tt.任务编码,
                                tt.用户流水号,
                                case when pr.LocalAddress is null then ate.现场地址 else pr.LocalAddress end as '现场地址',
                                tt.到达现场时刻,tt.生成任务时刻,
                                case when pr.[Name] is null then tae.患者姓名 else pr.Name end as '患者姓名',
                                tae.事件类型编码,    
								case when pr.PatientVersion is null then tzaet.名称  else pr.PatientVersion end as '事件类型',                               
                                司机=isnull(dbo.GetStr(tt.任务编码,3),''),                                
                                医生=isnull(dbo.GetStr(tt.任务编码,4),''),                              
                                护士=isnull(dbo.GetStr(tt.任务编码,5),''),
                                s.中心编码,
								case when pr.OriginalTaskType is null then tzaet.名称  else pr.OriginalTaskType end as '原事件类型', 
								case when pr.ContactTelephone is null then ate.联系电话  else pr.ContactTelephone end as '联系电话', 
								case when pr.ForArea is null then tae.区域  else pr.ForArea end as '区域',
								case when pr.[TaskCode] is null then '未填' else '已填' end as '状态',
                                case when pc.[TaskCode] is null then '未收' else '已收' end as '收费' 
                                from TTask tt
                                LEFT JOIN TAcceptEvent ate on ate.事件编码= tt.事件编码 and ate.受理序号=tt.受理序号 
                                LEFT JOIN TAlarmEvent tae on tae.事件编码= tt.事件编码
                                LEFT JOIN TZAlarmEventType tzaet on tae.事件类型编码 = tzaet.编码
                                LEFT JOIN TStation s ON tt.分站编码=s.编码 
            
                                 ";
                sbSQL.Append(sqlStr);
                sbSQL.Append(" left join ").Append(builder.InitialCatalog).Append(".dbo.M_PatientRecord  pr on pr.[TaskCode]=tt.任务编码");
                sbSQL.Append(" left join ").Append(builder.InitialCatalog).Append(".dbo.M_PatientCharge  pc on pc.[TaskCode]=tt.任务编码");
                sbSQL.Append(" where tt.生成任务时刻>='" + begintime + "' ");//
                sbSQL.Append(" and tt.生成任务时刻<'" + endtime + "' ");//
                WhereClauseUtility.AddStringEqual("tt.用户流水号", taskOrder, sbSQL);
                WhereClauseUtility.AddStringEqual("s.中心编码", centerCode, sbSQL);
                sbSQL.Append(" and (pr.SubmitLogo=1) ");//20151219取提交的病历
                sbSQL.Append(" order by tt.生成任务时刻 desc");

                DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.AttemperConnectionString, CommandType.Text, sbSQL.ToString(), null);
                List<MobileTaskInfo> list = new List<MobileTaskInfo>();
                if (ds.Tables[0].Rows.Count > 0)
                {
                    foreach (DataRow dr in ds.Tables[0].Rows)
                    {
                        MobileTaskInfo info = new MobileTaskInfo();
                        info.RenWuBianMa = dr["任务编码"].ToString();
                        info.YongHuLiuShuiHao = dr["用户流水号"].ToString();
                        info.XianChangDiZhi = dr["现场地址"].ToString();
                        info.DaoDaXianChangShiKe = dr["生成任务时刻"].ToString();
                        info.HuanZheXingMing = dr["患者姓名"].ToString();
                        info.EventType = dr["事件类型编码"].ToString();
                        info.EventTypeName = dr["事件类型"].ToString();
                        info.SiJi = dr["司机"].ToString();
                        info.YiSheng = dr["医生"].ToString();
                        info.HuShi = dr["护士"].ToString();
                        info.BingLi = dr["状态"].ToString();
                        info.ShouFei = dr["收费"].ToString();
                        info.OriginalTaskType = dr["原事件类型"].ToString();//20151211
                        info.ForHelpTelephone = dr["联系电话"].ToString();//20151211
                        info.ForArea = dr["区域"].ToString();//20151211
                        info.Blload = 1;
                        info.Sfload = 1;
                        list.Add(info);
                    }
                }

                return list;
            }
            catch (Exception ex)
            {
                List<MobileTaskInfo> listError = null;
                errorMsg = "系统错误：" + ex.Message;
                return listError;
            }
        }
        #endregion

        #region 根据工号获取中心编码
        /// <summary>
        /// 根据工号获取中心编码
        /// 20151218
        /// </summary>
        /// <param name="workCode"></param>
        /// <param name="centerCode"></param>
        public void GetCenterCode(string workCode, out string centerCode)
        {
            try
            {
                centerCode = "";
                StringBuilder sbSQL = new StringBuilder();//sql语句
                sbSQL.Append("declare @workCode varchar(10) ");
                sbSQL.Append("set @workCode='" + workCode + "' ");
                string sqlStr = @"   select   
                                中心编码,工号,姓名,分站编码,类型编码,是否有效
                                from TPerson tp
                                where tp.工号=@workCode ";


                sbSQL.Append(sqlStr);
                DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.AttemperConnectionString, CommandType.Text, sbSQL.ToString(), null);

                if (ds.Tables[0].Rows.Count > 0)
                {
                    centerCode = ds.Tables[0].Rows[0]["中心编码"].ToString();
                }


            }
            catch (Exception ex)
            {
                centerCode = "";
            }
        }
        #endregion

        #region 20151109根据表名得到主库字典数据(有效数据)
        /// 20151109增加为PAD，根据版本号和标识查询
        /// <summary>
        /// 得到主库字典数据(有效数据)
        /// </summary>
        /// <param name="eDictionary"></param>
        public List<I_Material> GetMainDictionary(string tableName, string version, string state)
        {
            m_TableName = tableName;
            string Conn = SqlHelper.AttemperConnectionString;
            return GetDictionary(Conn, version, state);
        }
        private List<I_Material> GetDictionary(string Conn, string version, string state)
        {
            I_Material info;
            List<I_Material> list = new List<I_Material>();
            StringBuilder strSQL = new StringBuilder();

            int eventDispatchCenterID = AppConfig.GetConfigInt("CurrentCenterBianMa"); //取config中配置的当前郊区中心在上海市统一调度库TCenter表中对应的编码 add2021-06-05 plq 

            if (m_TableName == "TStation")
            {
                //if (state == "0")
                //{
                //    strSQL.Append(" select distinct 编码=ts.编码,名称=ts.名称,实际标识='',分类='',分站编码=ts.编码,顺序号=isnull(ts.顺序号,1),ts.是否有效,ttt.修改标识,版本标识=case when t.版本标识='' then 0 else t.版本标识 end,上级名称='', ");
                //    strSQL.Append(" 拼音='',售价=null,收费刻度=null,给药方式='',最大限制金额=null from ( ");
                //    strSQL.Append(" select 修改数据主键,版本标识=max(版本标识) from TTrackTableChangeLog ");
                //    strSQL.Append(" where 版本标识>" + version + " and 表名='TStation' ");
                //    strSQL.Append(" group by 修改数据主键)t ");
                //    strSQL.Append(" left join TTrackTableChangeLog ttt on ttt.版本标识=t.版本标识 and ttt.修改数据主键=t.修改数据主键 ");
                //    strSQL.Append(" left join TStation ts on t.修改数据主键=ts.编码 ");
                //    strSQL.Append(" order by 顺序号");
                //}
                //else
                //{
                //    strSQL.Append(" select  编码,名称,实际标识='',分类='',分站编码='',顺序号=isnull(th.顺序号,1),是否有效,修改标识='',版本标识=isnull(t.版本标识,0),上级名称='', "); //将“顺序号=isnull(ts.顺序号,1)”改为“顺序号=isnull(th.顺序号,1)” 周志猛 2017-09-04
                //    strSQL.Append(" 拼音='',售价=null,收费刻度=null,给药方式='',最大限制金额=null from " + m_TableName + " th ");
                //    strSQL.Append(" left join (select 修改数据主键,版本标识=max(版本标识) from TTrackTableChangeLog ");
                //    strSQL.Append(" where 表名='" + m_TableName + "' ");
                //    strSQL.Append(" group by 修改数据主键)t on th.编码=t.修改数据主键 ");
                //    strSQL.Append(" where 是否有效=1 ");
                //    strSQL.Append(" order by 顺序号");
                //}

                //add2021-06-15 plq 适配V8调度库改造，TStation、TAmbulance、THospitalInfo三个表的表修改日志也放到管理库的TTrackTableChangeLog表中---但这三个表的修改日志谁来存???
                SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(SqlHelper.MainConnectionString);
                if (state == "0")
                {
                    strSQL.Append(" select distinct 编码=ts.编码,名称=ts.名称,实际标识='',分类='',分站编码=ts.编码,顺序号=isnull(ts.顺序号,1),ts.是否有效,ttt.修改标识,版本标识=case when t.版本标识='' then 0 else t.版本标识 end,上级名称='', ");
                    strSQL.Append(" 拼音='',售价=null,收费刻度=null,给药方式='',最大限制金额=null from ( ");
                    strSQL.Append(" select 修改数据主键,版本标识=max(版本标识) from  ");
                    strSQL.Append(builder.InitialCatalog).Append(".dbo.TTrackTableChangeLog ");
                    strSQL.Append(" where 版本标识>" + version + " and 表名='TStation' ");
                    strSQL.Append(" group by 修改数据主键)t ");
                    strSQL.Append(" left join  ").Append(builder.InitialCatalog).Append(".dbo.TTrackTableChangeLog ttt on ttt.版本标识=t.版本标识 and ttt.修改数据主键=t.修改数据主键 ");
                    strSQL.Append(" left join TStation ts on t.修改数据主键=ts.编码 ");
                    strSQL.Append("where ts.中心编码 = " + eventDispatchCenterID + ""); //add2021-06-05 plq 确保只取本中心数据
                    strSQL.Append(" order by 顺序号");
                }
                else
                {
                    strSQL.Append(" select  编码,名称,实际标识='',分类='',分站编码='',顺序号=isnull(th.顺序号,1),是否有效,修改标识='',版本标识=isnull(t.版本标识,0),上级名称='', "); //将“顺序号=isnull(ts.顺序号,1)”改为“顺序号=isnull(th.顺序号,1)” 周志猛 2017-09-04
                    strSQL.Append(" 拼音='',售价=null,收费刻度=null,给药方式='',最大限制金额=null from " + m_TableName + " th ");
                    strSQL.Append(" left join (select 修改数据主键,版本标识=max(版本标识) from  ");
                    strSQL.Append(builder.InitialCatalog).Append(".dbo.TTrackTableChangeLog ");
                    strSQL.Append(" where 表名='" + m_TableName + "' ");
                    strSQL.Append(" group by 修改数据主键)t on th.编码=t.修改数据主键 ");
                    strSQL.Append(" where 是否有效=1 ");
                    strSQL.Append("and th.中心编码 = " + eventDispatchCenterID + ""); //add2021-06-05 plq 确保只取本中心数据
                    strSQL.Append(" order by 顺序号");
                }
            }
            else if (m_TableName == "TAmbulance")
            {
                //if (state == "0")
                //{
                //    strSQL.Append(" select distinct 编码=ta.车辆编码,名称=ta.车牌号码,ta.实际标识,分类='',ta.分站编码,顺序号=1,ta.是否有效,ttt.修改标识,版本标识=case when t.版本标识='' then 0 else t.版本标识 end,上级名称='',");
                //    strSQL.Append(" 拼音='',售价=null,收费刻度=null,给药方式='',最大限制金额=null from ( ");
                //    strSQL.Append(" select 修改数据主键,版本标识=max(版本标识) from TTrackTableChangeLog ");
                //    strSQL.Append(" where 版本标识>" + version + " and 表名='TAmbulance' ");
                //    strSQL.Append(" group by 修改数据主键)t ");
                //    strSQL.Append(" left join TTrackTableChangeLog ttt on ttt.版本标识=t.版本标识 and ttt.修改数据主键=t.修改数据主键 ");
                //    strSQL.Append(" left join TAmbulance ta on t.修改数据主键=ta.车辆编码 ");
                //    strSQL.Append(" order by ta.车牌号码");
                //}
                //else
                //{
                //    strSQL.Append(" select 编码=车辆编码,名称=车牌号码,实际标识,分类='',分站编码,顺序号=1,是否有效,修改标识='',版本标识=isnull(t.版本标识,0),上级名称='', ");
                //    strSQL.Append(" 拼音='',售价=null,收费刻度=null,给药方式='',最大限制金额=null from " + m_TableName + " th ");
                //    strSQL.Append(" left join (select 修改数据主键,版本标识=max(版本标识) from TTrackTableChangeLog ");
                //    strSQL.Append(" where 表名='" + m_TableName + "' ");
                //    strSQL.Append(" group by 修改数据主键)t on th.车辆编码=t.修改数据主键 ");
                //    strSQL.Append(" where th.是否有效=1 ");
                //    strSQL.Append(" order by 车牌号码");
                //}

                //add2021-06-15 plq 适配V8调度库改造，TStation、TAmbulance、THospitalInfo三个表的表修改日志也放到管理库的TTrackTableChangeLog表中---但这三个表的修改日志谁来存???
                SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(SqlHelper.MainConnectionString);
                if (state == "0")
                {
                    strSQL.Append(" select distinct 编码=ta.车辆编码,名称=ta.车牌号码,ta.实际标识,分类='',ta.分站编码,顺序号=1,ta.是否有效,ttt.修改标识,版本标识=case when t.版本标识='' then 0 else t.版本标识 end,上级名称='',");
                    strSQL.Append(" 拼音='',售价=null,收费刻度=null,给药方式='',最大限制金额=null from ( ");
                    strSQL.Append(" select 修改数据主键,版本标识=max(版本标识) from  ");
                    strSQL.Append(builder.InitialCatalog).Append(".dbo.TTrackTableChangeLog ");
                    strSQL.Append(" where 版本标识>" + version + " and 表名='TAmbulance' ");
                    strSQL.Append(" group by 修改数据主键)t ");
                    strSQL.Append(" left join ").Append(builder.InitialCatalog).Append(".dbo.TTrackTableChangeLog ttt on ttt.版本标识=t.版本标识 and ttt.修改数据主键=t.修改数据主键 ");
                    strSQL.Append(" left join TAmbulance ta on t.修改数据主键=ta.车辆编码 ");
                    strSQL.Append(" left join TStation ts on ts.编码=ta.分站编码 "); //add2021-06-05 plq 确保只取本中心数据
                    strSQL.Append(" where 1=1 ");
                    strSQL.Append(" and ts.中心编码 = " + eventDispatchCenterID + ""); //add2021-06-05 plq 确保只取本中心数据
                    strSQL.Append(" order by ta.车牌号码");
                }
                else
                {
                    strSQL.Append(" select 编码=车辆编码,名称=车牌号码,实际标识,分类='',分站编码,顺序号=1,是否有效,修改标识='',版本标识=isnull(t.版本标识,0),上级名称='', ");
                    strSQL.Append(" 拼音='',售价=null,收费刻度=null,给药方式='',最大限制金额=null from " + m_TableName + " th ");
                    strSQL.Append(" left join (select 修改数据主键,版本标识=max(版本标识) from  ");
                    strSQL.Append(builder.InitialCatalog).Append(".dbo.TTrackTableChangeLog ");
                    strSQL.Append(" where 表名='" + m_TableName + "' ");
                    strSQL.Append(" group by 修改数据主键)t on th.车辆编码=t.修改数据主键 ");
                    strSQL.Append(" left join TStation ts on ts.编码=th.分站编码 "); //add2021-06-05 plq 确保只取本中心数据
                    strSQL.Append(" where th.是否有效=1 ");
                    strSQL.Append(" and ts.中心编码 = " + eventDispatchCenterID + ""); //add2021-06-05 plq 确保只取本中心数据
                    strSQL.Append(" order by 车牌号码");
                }
            }
            else if (m_TableName == "THospitalInfo")
            {
                //if (state == "0")
                //{
                //    strSQL.Append(" select distinct 编码=th.编码,名称=th.名称,实际标识='',分类='',分站编码='',顺序号=isnull(th.顺序号,1),th.是否有效,ttt.修改标识,版本标识=case when t.版本标识='' then 0 else t.版本标识 end,上级名称='', ");
                //    strSQL.Append(" 拼音='',售价=null,收费刻度=null,给药方式='',最大限制金额=null from ( ");
                //    strSQL.Append(" select 修改数据主键,版本标识=max(版本标识) from TTrackTableChangeLog ");
                //    strSQL.Append(" where 版本标识>" + version + " and 表名='THospitalInfo' ");
                //    strSQL.Append(" group by 修改数据主键)t ");
                //    strSQL.Append(" left join TTrackTableChangeLog ttt on ttt.版本标识=t.版本标识 and ttt.修改数据主键=t.修改数据主键 ");
                //    strSQL.Append(" left join THospitalInfo th on t.修改数据主键=th.编码 ");
                //    strSQL.Append(" order by 顺序号");
                //}
                //else
                //{
                //    strSQL.Append(" select 编码,名称,实际标识='',分类='',分站编码='',顺序号=isnull(th.顺序号,1),是否有效,修改标识='',版本标识=isnull(t.版本标识,0),上级名称='', ");
                //    strSQL.Append(" 拼音='',售价=null,收费刻度=null,给药方式='',最大限制金额=null from " + m_TableName + " th ");
                //    strSQL.Append(" left join (select 修改数据主键,版本标识=max(版本标识) from TTrackTableChangeLog ");
                //    strSQL.Append(" where 表名='" + m_TableName + "' ");
                //    strSQL.Append(" group by 修改数据主键)t on th.编码=t.修改数据主键 ");
                //    strSQL.Append(" where th.是否有效=1 ");
                //    strSQL.Append(" order by 顺序号");
                //}

                //add2021-06-15 plq 适配V8调度库改造，TStation、TAmbulance、THospitalInfo三个表的表修改日志也放到管理库的TTrackTableChangeLog表中---但这三个表的修改日志谁来存???
                SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(SqlHelper.MainConnectionString);
                if (state == "0")
                {
                    strSQL.Append(" select distinct 编码=th.编码,名称=th.名称,实际标识='',分类='',分站编码='',顺序号=isnull(th.顺序号,1),th.是否有效,ttt.修改标识,版本标识=case when t.版本标识='' then 0 else t.版本标识 end,上级名称='', ");
                    strSQL.Append(" 拼音=th.拼音头,售价=null,收费刻度=null,给药方式='',最大限制金额=null from ( ");
                    strSQL.Append(" select 修改数据主键,版本标识=max(版本标识) from  ");
                    strSQL.Append(builder.InitialCatalog).Append(".dbo.TTrackTableChangeLog ");
                    strSQL.Append(" where 版本标识>" + version + " and 表名='THospitalInfo' ");
                    strSQL.Append(" group by 修改数据主键)t ");
                    strSQL.Append(" left join ").Append(builder.InitialCatalog).Append(".dbo.TTrackTableChangeLog ttt on ttt.版本标识=t.版本标识 and ttt.修改数据主键=t.修改数据主键 ");
                    strSQL.Append(" left join THospitalInfo th on t.修改数据主键=th.编码 ");
                    //strSQL.Append(" and th.中心编码 = " + eventDispatchCenterID + ""); //add2021-06-05 plq 确保只取本中心数据
                    strSQL.Append(" order by 顺序号");
                }
                else
                {
                    strSQL.Append(" select 编码,名称,实际标识='',分类='',分站编码='',顺序号=isnull(th.顺序号,1),是否有效,修改标识='',版本标识=isnull(t.版本标识,0),上级名称='', ");
                    strSQL.Append(" 拼音=th.拼音头,售价=null,收费刻度=null,给药方式='',最大限制金额=null from " + m_TableName + " th ");
                    strSQL.Append(" left join (select 修改数据主键,版本标识=max(版本标识) from  ");
                    strSQL.Append(builder.InitialCatalog).Append(".dbo.TTrackTableChangeLog ");
                    strSQL.Append(" where 表名='" + m_TableName + "' ");
                    strSQL.Append(" group by 修改数据主键)t on th.编码=t.修改数据主键 ");
                    strSQL.Append(" where th.是否有效=1 ");
                    //strSQL.Append(" and th.中心编码 = " + eventDispatchCenterID + ""); //add2021-06-05 plq 确保只取本中心数据
                    strSQL.Append(" order by 顺序号");
                }
            }
            else if (m_TableName == "I_Material")
            {
                Conn = SqlHelper.MainConnectionString;
                if (state == "0")
                {
                    strSQL.Append(" select distinct 编码=th.ID,名称=th.Name,实际标识=case when [OtherTypeID]='PRMeasureType-99' then '检查' when (([OtherTypeID] like 'PRMeasureType-%') and [OtherTypeID]!='PRMeasureType-99') then '治疗' when [OtherTypeID] like 'PRDrugType-%' then '药品' else '耗材' end,分类=OtherTypeID, ");
                    strSQL.Append(" 分站编码=th.Specification,顺序号=isnull(th.SN,1),是否有效=th.IsActive,ttt.修改标识,版本标识=case when t.版本标识='' then 0 else t.版本标识 end,上级名称=td.Name, ");
                    strSQL.Append(" 拼音=th.PinYin,售价=th.RealPrice,收费刻度=th.FeeScale,给药方式=th.GiveMedicineWay,最大限制金额=th.LimitMaxPrice from ( ");
                    strSQL.Append(" select 修改数据主键,版本标识=max(版本标识) from TTrackTableChangeLog ");
                    strSQL.Append(" where 版本标识>" + version + " and 表名='I_Material' ");
                    strSQL.Append(" group by 修改数据主键)t ");
                    strSQL.Append(" left join TTrackTableChangeLog ttt on ttt.版本标识=t.版本标识 and ttt.修改数据主键=t.修改数据主键 ");
                    strSQL.Append(" left join I_Material th on t.修改数据主键=th.ID ");
                    strSQL.Append(" left join [TDictionary] td on th.OtherTypeID=td.ID ");
                    strSQL.Append(" where td.ParentID!='-1' and td.TypeID in ('PRDrugType','PRMeasureType','PRConsumableType') and isnull(YBCode,'') not like '%[a-zA-Z]%' ");
                    strSQL.Append(" order by 顺序号");
                }
                else
                {
                    strSQL.Append(" select 编码=th.ID,名称=th.Name,实际标识=case when [OtherTypeID]='PRMeasureType-99' then '检查' when (([OtherTypeID] like 'PRMeasureType-%') and [OtherTypeID]!='PRMeasureType-99') then '治疗' when [OtherTypeID] like 'PRDrugType-%' then '药品' else '耗材' end,分类=OtherTypeID, ");
                    strSQL.Append(" 分站编码=th.Specification,顺序号=isnull(th.SN,1),是否有效=th.IsActive,修改标识='',版本标识=isnull(t.版本标识,0),上级名称=td.Name,  ");
                    strSQL.Append(" 拼音=th.PinYin,售价=th.RealPrice,收费刻度=th.FeeScale,给药方式=th.GiveMedicineWay,最大限制金额=th.LimitMaxPrice from " + m_TableName + " th ");
                    strSQL.Append(" left join [TDictionary] td on th.OtherTypeID=td.ID ");
                    strSQL.Append(" left join (select 修改数据主键,版本标识=max(版本标识) from TTrackTableChangeLog ");
                    strSQL.Append(" where 表名='I_Material' ");
                    strSQL.Append(" group by 修改数据主键)t on th.ID=t.修改数据主键 ");
                    strSQL.Append(" where th.IsActive=1 and td.ParentID!='-1' and td.TypeID in ('PRDrugType','PRMeasureType','PRConsumableType') and isnull(YBCode,'') not like '%[a-zA-Z]%'  ");
                    strSQL.Append(" order by 顺序号");
                }
            }
            else if (m_TableName == "M_Dictionary")
            {
                Conn = SqlHelper.MainConnectionString;
                if (state == "0")
                {
                    strSQL.Append(" select distinct 编码=th.ID,名称=th.Name,实际标识=th.TypeID,分类='',分站编码='',顺序号=isnull(th.SN,1),是否有效=isnull(th.IsActive,0),ttt.修改标识,版本标识=case when t.版本标识='' then 0 else t.版本标识 end,上级名称='',  ");
                    strSQL.Append(" 拼音='',售价=null,收费刻度=null,给药方式='',最大限制金额=null from ( ");
                    strSQL.Append(" select 修改数据主键,版本标识=max(版本标识) from TTrackTableChangeLog ");
                    strSQL.Append(" where 版本标识>" + version + " and 表名='M_Dictionary' ");
                    strSQL.Append(" group by 修改数据主键)t ");
                    strSQL.Append(" left join TTrackTableChangeLog ttt on ttt.版本标识=t.版本标识 and ttt.修改数据主键=t.修改数据主键 ");
                    strSQL.Append(" left join M_Dictionary th on t.修改数据主键=th.ID ");
                    strSQL.Append(" order by 顺序号");
                }
                else
                {
                    strSQL.Append(" select 编码=th.ID,名称=th.Name,实际标识=th.TypeID,分类='',分站编码='',顺序号=isnull(th.SN,1),是否有效=isnull(th.IsActive,0),修改标识='',版本标识=isnull(t.版本标识,0),上级名称='',  ");
                    strSQL.Append(" 拼音='',售价=null,收费刻度=null,给药方式='',最大限制金额=null from " + m_TableName + " th ");
                    strSQL.Append(" left join (select 修改数据主键,版本标识=max(版本标识) from TTrackTableChangeLog ");
                    strSQL.Append(" where 表名='" + m_TableName + "' ");
                    strSQL.Append(" group by 修改数据主键)t on th.ID=t.修改数据主键 ");
                    strSQL.Append(" where th.IsActive=1 ");
                    strSQL.Append(" order by 顺序号");
                }
            }
            else if (m_TableName == "M_DictionaryType")
            {
                Conn = SqlHelper.MainConnectionString;
                if (state == "0")
                {
                    strSQL.Append(" select distinct 编码=th.ID,名称=th.[Description],实际标识=th.TypeID,分类='',分站编码='',顺序号=1,是否有效=isnull(th.IsActive,0),ttt.修改标识,版本标识=case when t.版本标识='' then 0 else t.版本标识 end,上级名称='',  ");
                    strSQL.Append(" 拼音='',售价=null,收费刻度=null,给药方式='',最大限制金额=null from ( ");
                    strSQL.Append(" select 修改数据主键,版本标识=max(版本标识) from TTrackTableChangeLog ");
                    strSQL.Append(" where 版本标识>" + version + " and 表名='M_DictionaryType' ");
                    strSQL.Append(" group by 修改数据主键)t ");
                    strSQL.Append(" left join TTrackTableChangeLog ttt on ttt.版本标识=t.版本标识 and ttt.修改数据主键=t.修改数据主键 ");
                    strSQL.Append(" left join M_DictionaryType th on t.修改数据主键=th.ID ");
                }
                else
                {
                    strSQL.Append(" select 编码=th.ID,名称=th.[Description],实际标识=th.TypeID,分类='',分站编码='',顺序号=1,是否有效=isnull(th.IsActive,0),修改标识='',版本标识=isnull(t.版本标识,0),上级名称='',  ");
                    strSQL.Append(" 拼音='',售价=null,收费刻度=null,给药方式='',最大限制金额=null from " + m_TableName + " th ");
                    strSQL.Append(" left join (select 修改数据主键,版本标识=max(版本标识) from TTrackTableChangeLog ");
                    strSQL.Append(" where 表名='" + m_TableName + "' ");
                    strSQL.Append(" group by 修改数据主键)t on th.ID=t.修改数据主键 ");
                    strSQL.Append(" where th.IsActive=1 ");
                }
            }
            else if (m_TableName == "M_ZCaseTemplate")
            {
                //20151127病种分类字典表
                Conn = SqlHelper.MainConnectionString;
                if (state == "0")
                {
                    strSQL.Append(" select distinct 编码=th.ID,名称=th.Name,实际标识=Convert(nvarchar(1000),th.AlarmReason),分类='',分站编码=Convert(nvarchar(1000),th.HistoryOfPresentIllness),顺序号=isnull(th.SN,1),是否有效=th.IsActive,ttt.修改标识,版本标识=case when t.版本标识='' then 0 else t.版本标识 end,上级名称='',  ");
                    strSQL.Append(" 拼音='',售价=null,收费刻度=null,给药方式='',最大限制金额=null from ( ");
                    strSQL.Append(" select 修改数据主键,版本标识=max(版本标识) from TTrackTableChangeLog ");
                    strSQL.Append(" where 版本标识>" + version + " and 表名='M_ZCaseTemplate' ");
                    strSQL.Append(" group by 修改数据主键)t ");
                    strSQL.Append(" left join TTrackTableChangeLog ttt on ttt.版本标识=t.版本标识 and ttt.修改数据主键=t.修改数据主键 ");
                    strSQL.Append(" left join M_ZCaseTemplate th on t.修改数据主键=th.ID ");
                }
                else
                {
                    strSQL.Append(" select 编码=th.ID,名称=th.[Name],实际标识=Convert(nvarchar(1000),th.AlarmReason),分类='',分站编码=Convert(nvarchar(1000),th.HistoryOfPresentIllness),顺序号=isnull(th.SN,1),是否有效=th.IsActive,修改标识='',版本标识=isnull(t.版本标识,0),上级名称='',  ");
                    strSQL.Append(" 拼音='',售价=null,收费刻度=null,给药方式='',最大限制金额=null from " + m_TableName + " th ");
                    strSQL.Append(" left join (select 修改数据主键,版本标识=max(版本标识) from TTrackTableChangeLog ");
                    strSQL.Append(" where 表名='" + m_TableName + "' ");
                    strSQL.Append(" group by 修改数据主键)t on th.ID=t.修改数据主键 ");
                    strSQL.Append(" where th.IsActive=1 ");
                }
            }
            else if (m_TableName == "M_ZECGImpression" || m_TableName == "M_ZICDNew" || m_TableName == "M_ZSymptomPendingInvestigation")
            {
                //20151127心电图印象字典表、初步印象字典表、症状待查字典表
                Conn = SqlHelper.MainConnectionString;
                if (state == "0")
                {
                    strSQL.Append(" select distinct 编码=th.ID,名称=th.Name,实际标识=th.ParentID,分类='',分站编码='',顺序号=isnull(th.SN,1),是否有效=th.IsActive,ttt.修改标识,版本标识=case when t.版本标识='' then 0 else t.版本标识 end,上级名称='',  ");
                    strSQL.Append(" 拼音=th.PinYin,售价=null,收费刻度=null,给药方式='',最大限制金额=null from ( ");
                    strSQL.Append(" select 修改数据主键,版本标识=max(版本标识) from TTrackTableChangeLog ");
                    strSQL.Append(" where 版本标识>" + version + " and 表名='" + m_TableName + "' ");
                    strSQL.Append(" group by 修改数据主键)t ");
                    strSQL.Append(" left join TTrackTableChangeLog ttt on ttt.版本标识=t.版本标识 and ttt.修改数据主键=t.修改数据主键 ");
                    strSQL.Append(" left join " + m_TableName + " th on t.修改数据主键=th.ID ");
                }
                else
                {
                    strSQL.Append(" select 编码=th.ID,名称=th.[Name],实际标识=th.ParentID,分类='',分站编码='',顺序号=isnull(th.SN,1),是否有效=th.IsActive,修改标识='',版本标识=isnull(t.版本标识,0),上级名称='',  ");
                    strSQL.Append(" 拼音=th.PinYin,售价=null,收费刻度=null,给药方式='',最大限制金额=null from " + m_TableName + " th ");
                    strSQL.Append(" left join (select 修改数据主键,版本标识=max(版本标识) from TTrackTableChangeLog ");
                    strSQL.Append(" where 表名='" + m_TableName + "' ");
                    strSQL.Append(" group by 修改数据主键)t on th.ID=t.修改数据主键 ");
                    strSQL.Append(" where th.IsActive=1 ");
                }
            }
            //else
            //{
            //    strSQL.Append(" select 编码,名称,顺序号,是否有效 from " + m_TableName + " ");
            //    strSQL.Append(" where 是否有效=1 order by 顺序号");
            //}
            try
            {
                using (DataSet ds = SqlHelper.ExecuteDataSet(Conn, CommandType.Text, strSQL.ToString(), null))
                {
                    foreach (DataRow dr in ds.Tables[0].Rows)
                    {
                        info = new I_Material();
                        info.MTypeID = DBConvert.ConvertStringToString(dr["编码"]);
                        info.Name = DBConvert.ConvertStringToString(dr["名称"]);
                        info.OtherTypeID = DBConvert.ConvertStringToString(dr["实际标识"]);
                        info.Specification = DBConvert.ConvertStringToString(dr["分站编码"]);
                        info.SN = Convert.ToInt32(dr["顺序号"]);
                        info.IsActive = Convert.ToBoolean(dr["是否有效"]);
                        info.Other1 = DBConvert.ConvertStringToString(dr["修改标识"]);
                        info.Other2 = DBConvert.ConvertStringToString(dr["版本标识"]);
                        info.PinYin = DBConvert.ConvertStringToString(dr["拼音"]);
                        info.RealPrice = DBConvert.ConvertDBTypeToNullableDecimal(dr["售价"]);
                        info.FeeScale = DBConvert.ConvertDBTypeToNullableInt(dr["收费刻度"]);
                        info.GiveMedicineWay = DBConvert.ConvertStringToString(dr["给药方式"]);
                        info.LimitMaxPrice = DBConvert.ConvertDBTypeToNullableInt(dr["最大限制金额"]);
                        info.MCode = DBConvert.ConvertStringToString(dr["上级名称"]);//20151210增加
                        info.ProjectCode = DBConvert.ConvertStringToString(dr["分类"]);//20151220增加
                        info.PersonAlarmCount = -1; //add2021-10-18 plq 医保上线移植
                        list.Add(info);
                    }
                    return list;
                }
            }
            catch (Exception)
            {
                //Log4Net.LogError("DictionaryDAL/GetDictionary", ex.Message);
                return null;
            }
        }
        #endregion

        #region PAD20151210-接收收费信息
        /// <summary>
        /// PAD20151210-接收收费信息
        /// </summary>
        /// <param name="info"></param>
        /// <param name="patientChargeLogInfo"></param>
        /// <param name="errorMsg"></param>
        /// <returns></returns>
        public bool MobileSavePatientCharge(string TaskCode, int PatientOrder, M_PatientCharge info, M_PatientChargeLog patientChargeLogInfo, List<M_PatientChargeDetail> patientChargeDetailInfo, List<M_PatientChargeDetailLog> patientChargeDetailLogInfo, bool Isvalid, ref string errorMsg)
        {

            using (var tran = db.Database.BeginTransaction())
            {
                try
                {
                    //1 先查询收费主表是否存在
                    if (info != null)
                    {
                        M_PatientCharge patientCharge = (from e in db.M_PatientCharge
                                                         where e.TaskCode == info.TaskCode && e.PatientOrder == info.PatientOrder
                                                         select e).FirstOrDefault();
                        if (patientCharge != null)
                        {
                            //从查询的数据里把原来的值传过去，因为PAD那边没有这些字段
                            info.AddressStart = patientCharge.AddressStart;
                            info.AddressEnd = patientCharge.AddressEnd;
                            info.OutStationRoadCode = patientCharge.OutStationRoadCode;
                            info.ReturnStationRoadCode = patientCharge.ReturnStationRoadCode;
                            info.ReceivablesPaidInconsistentReasons = patientCharge.ReceivablesPaidInconsistentReasons;
                            info.BackUp1 = patientCharge.BackUp1;

                            dalContext.IM_PatientChargeDAL.Del(patientCharge);//先删除

                        }
                        dalContext.IM_PatientChargeDAL.Add(info);//再增加
                    }

                    //1 再查询收费日志表是否存在
                    if (patientChargeLogInfo != null)
                    {
                        M_PatientChargeLog patientChargeLog = (from e in db.M_PatientChargeLog
                                                               where e.TaskCode == patientChargeLogInfo.TaskCode && e.PatientOrder == patientChargeLogInfo.PatientOrder && e.InvoiceNumber == patientChargeLogInfo.InvoiceNumber
                                                               select e).FirstOrDefault();
                        if (patientChargeLog != null)
                        {
                            dalContext.IM_PatientChargeLogDAL.Del(patientChargeLog);//先删除
                        }
                        if (patientChargeLogInfo.Isvalid == true)
                        {
                            //如果传的日志表Isvalid为true，根据任务编码和序号把数据库里面的所有数据都更改为false;
                            M_PatientChargeLog log = new M_PatientChargeLog();
                            log.TaskCode = patientChargeLogInfo.TaskCode;
                            log.PatientOrder = patientChargeLogInfo.PatientOrder;
                            log.Isvalid = false;//
                            dalContext.IM_PatientChargeLogDAL.ModifyBy(log, (p => p.TaskCode == log.TaskCode && p.PatientOrder == log.PatientOrder), "Isvalid"); //把之前的数据都更改为无效
                        }
                        dalContext.IM_PatientChargeLogDAL.Add(patientChargeLogInfo);//再增加
                    }

                    //1 保存收费子表--20210426
                    if (patientChargeDetailInfo != null)
                    {
                        //1 再查询收费子表是否存在
                        var dqry0 = from infos in db.M_PatientChargeDetail
                                    where infos.TaskCode == info.TaskCode && infos.PatientOrder == info.PatientOrder
                                    select infos;
                        foreach (var inf in dqry0)
                            db.M_PatientChargeDetail.Remove(inf);//删除收费子表

                        List<M_PatientChargeDetail> patientChargeDetail = new List<M_PatientChargeDetail>();
                        for (int k = 0; k < patientChargeDetailInfo.Count; k++)
                        {
                            M_PatientChargeDetail SInfo = patientChargeDetailInfo[k];
                            SInfo.TaskCode = SInfo.TaskCode;
                            SInfo.PatientOrder = SInfo.PatientOrder;
                            SInfo.ChargeOrder = k + 1; ;//收费序号
                            SInfo.ChargeDate = SInfo.ChargeDate;
                            SInfo.PaidMoney = SInfo.PaidMoney;
                            SInfo.ChargeType = SInfo.ChargeType;
                            SInfo.OrderNumber = SInfo.OrderNumber;
                            SInfo.IFRefund = SInfo.IFRefund;
                            patientChargeDetail.Add(SInfo);
                        }
                        db.M_PatientChargeDetail.AddRange(patientChargeDetail);//插入收费子表

                    }

                    //1 保存收费子表日志表--20210426
                    if (patientChargeDetailLogInfo != null)
                    {
                        if (Isvalid == true)
                        {
                            //如果传的日志表Isvalid为true，根据任务编码和序号把数据库里面的所有数据都更改为false;
                            M_PatientChargeDetailLog log = new M_PatientChargeDetailLog();
                            log.TaskCode = TaskCode;
                            log.PatientOrder = PatientOrder;
                            log.Isvalid = false;//
                            dalContext.IM_PatientChargeDetailLogDAL.ModifyBy(log, (p => p.TaskCode == log.TaskCode && p.PatientOrder == log.PatientOrder), "Isvalid"); //把之前的数据都更改为无效

                        }

                        db.M_PatientChargeDetailLog.AddRange(patientChargeDetailLogInfo);//插入收费子表日志表

                    }

                    db.SaveChanges();//将在此上下文中所做的所有更改保存到基础数据库
                    tran.Commit(); //提交事务

                    return true;
                }
                catch (Exception ex)
                {
                    if (tran != null)
                        tran.Rollback();  //回滚事务
                    errorMsg = "收费上传失败！ 操作已取消！~~" + ex.Message;
                    return false;
                }
            }
        }
        #endregion

        #region PAD20151210根据任务编码序号查询收费主表信息
        /// <summary>
        /// PAD20151210根据任务编码序号查询收费主表信息
        /// 20211025 zll 添加根据任务编码查询收费子表信息  //2021-12-06 plq 医保移植
        /// </summary>
        /// <param name="taskCode"></param>
        /// <param name="patientOrder"></param>
        /// <param name="info"></param>
        public void GetPatientChargeInfo(string taskCode, int patientOrder, out M_PatientCharge info, out List<M_PatientChargeDetail> pcDetail)
        {
            info = dalContext.IM_PatientChargeDAL.GetModelWithOutTrace(a => a.TaskCode == taskCode && a.PatientOrder == patientOrder);
            pcDetail = dalContext.IM_PatientChargeDetailDAL.GetListBy(b => b.PatientOrder == patientOrder && b.TaskCode == taskCode);

        }
        #endregion

        #region PAD病历相关

        #region PAD 查询已有病历三大主表
        /// <summary>
        /// PAD 查询已有病历
        /// </summary>
        /// <param name="taskCode"></param>
        /// <param name="patientOrder"></param>
        /// <param name="info"></param>
        /// <param name="pra"></param>
        public void GetPADPatientInfo(string taskCode, int patientOrder, out object info
           , out M_PatientRecordAppend pra, out M_PatientRecordCPR prc)
        {
            info = dalContext.IM_PatientRecordDAL.GetModelWithOutTrace(a => a.TaskCode == taskCode && a.PatientOrder == patientOrder);

            pra = dalContext.IM_PatientRecordAppendDAL.GetModelWithOutTrace(a => a.TaskCode == taskCode && a.PatientOrder == patientOrder);

            prc = dalContext.IM_PatientRecordCPRDAL.GetModelWithOutTrace(a => a.TaskCode == taskCode && a.PatientOrder == patientOrder);

        }
        #endregion

        #region PAD20151210获取病历救治记录主表、措施、耗材、药品子表
        public void GetPRRescueMeasureInfos(string taskCode, int patientOrder, out List<M_PatientRecordRescue> prrs
           , out  List<M_PatientRecordMeasure> prms, out  List<M_PatientRecordDrug> prds, out  List<M_PatientRecordSanitation> prss)
        {
            prrs = dalContext.IM_PatientRecordRescueDAL.GetListBy((a => a.TaskCode == taskCode && a.PatientOrder == patientOrder));

            prms = dalContext.IM_PatientRecordMeasureDAL.GetListBy(a => a.PatientOrder == patientOrder && a.TaskCode == taskCode);

            prds = dalContext.IM_PatientRecordDrugDAL.GetListBy(a => a.PatientOrder == patientOrder && a.TaskCode == taskCode);
            prss = dalContext.IM_PatientRecordSanitationDAL.GetListBy(a => a.PatientOrder == patientOrder && a.TaskCode == taskCode);
        }
        #endregion

        #region PAD用--根据用户流水号取任务编码20150714  2016-09-27吴涛
        public string GetTaskCodeByTaskOrder(string TaskOrder)
        {
            try
            {
                if (TaskOrder == "")
                {
                    TaskOrder = "100402zx1014";//测试用
                }
                string Part = TaskOrder.Substring(0, 5);
                StringBuilder sbSQL = new StringBuilder();
                sbSQL.Append("declare @TaskCodeB char(20) ");
                sbSQL.Append("declare @TaskCodeE char(20) ");
                sbSQL.Append("set @TaskCodeB = '20'+'" + Part + "'+'0000000000000' ");
                sbSQL.Append("set @TaskCodeE = '20'+'" + Part + "'+'9999999999999' ");

                sbSQL.Append(" select 任务编码");
                sbSQL.Append(" from TTask tt");
                sbSQL.Append(" where 任务编码>@TaskCodeB and tt.任务编码<=@TaskCodeE  ");
                sbSQL.Append(" and 用户流水号='").Append(TaskOrder).Append("' ");
                DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.AttemperConnectionString, CommandType.Text, sbSQL.ToString(), null);
                string TaskCode = "";
                if (ds.Tables[0].Rows.Count > 0)
                {
                    TaskCode = ds.Tables[0].Rows[0][0].ToString();
                }
                else
                {
                    TaskCode = "";
                }
                return TaskCode;
            }
            catch (Exception ex)
            {
                LogUtility.Error("MobileTaskDAL/GetTaskCodeByTaskOrder()", ex.ToString());
                return "";
            }
        }
        #endregion

        #region 新增病历主表和附表

        public bool InsertPAD(object info, M_PatientRecordAppend pra
            , M_PatientRecordCPR prCPR, List<M_PatientRecordDiag> prDiag
            , List<M_PatientRecordECGImpressions> prECG
            , List<M_PatientRecordRescue> prRescue, List<M_PatientRecordMeasure> prMeasure
            , List<M_PatientRecordDrug> prDrug, List<M_PatientRecordSanitation> prSanitation
            , List<M_PatientRecordLossDrug> prLossDrug, List<M_PatientRecordLossSanitation> prLossSanitation)
        {
            using (var tran = db.Database.BeginTransaction())
            {
                string IMEI = "";
                try
                {
                    M_PatientRecord pInfo = (M_PatientRecord)info;

                    //pInfo.MedicalRecordGenerationTime = DateTime.Now;//病历生成时间
                    db.M_PatientRecord.Add(pInfo);//插入病历主表
                    IMEI = pInfo.IMEI;//20150827判断是PC填写还是PAD填写

                    if (pra != null)
                    {
                        db.M_PatientRecordAppend.Add(pra);//插入病历附表--体检等
                    }
                    if (prCPR != null)
                    {
                        //prCPR.RegistrationTime = DateTime.Now;//登记时间
                        db.M_PatientRecordCPR.Add(prCPR);//插入病历附表--心肺复苏
                    }
                    if (prDiag != null)
                    {
                        db.M_PatientRecordDiag.AddRange(prDiag);//插入初步诊断子表
                    }
                    if (prECG != null)
                    {
                        db.M_PatientRecordECGImpressions.AddRange(prECG);//插入心电图印象子表
                    }

                    if (prRescue != null)
                    {
                        db.M_PatientRecordRescue.AddRange(prRescue);//插入救治记录主表
                    }
                    if (prMeasure != null)
                    {
                        db.M_PatientRecordMeasure.AddRange(prMeasure);//插入救治措施子表
                    }
                    if (prDrug != null)
                    {
                        db.M_PatientRecordDrug.AddRange(prDrug);//插入药品子表
                    }
                    if (prSanitation != null)
                    {
                        db.M_PatientRecordSanitation.AddRange(prSanitation);//插入耗材子表
                    }
                    if (prLossDrug != null)
                    {
                        db.M_PatientRecordLossDrug.AddRange(prLossDrug);//插入损耗药品子表--扩展用
                    }
                    if (prLossSanitation != null)
                    {
                        db.M_PatientRecordLossSanitation.AddRange(prLossSanitation);//插入损耗卫生材料子表--扩展用
                    }

                    db.SaveChanges();//将在此上下文中所做的所有更改保存到基础数据库
                    tran.Commit(); //提交事务
                    //transaction.Complete();//这一句如果注释后，则上面的保存不会被提交到DB中
                    return true;
                }
                catch (Exception ex)
                {
                    LogUtility.Error("MobileTaskDAL/InsertPAD", info.ToString() + pra.ToString() + prCPR.ToString() + prDiag.ToString() + prECG.ToString() + prRescue.ToString() + prMeasure.ToString() + prDrug.ToString() + prSanitation.ToString() + prLossDrug.ToString() + prLossSanitation.ToString());
                    LogUtility.Error("MobileTaskDAL/InsertPAD(" + IMEI + ")", ex.ToString());
                    if (tran != null)
                        tran.Rollback();  //回滚事务
                    return false;
                }
            }
        }
        #endregion

        #region 修改病历表
        public bool UpdatePAD(object info, M_PatientRecordAppend pra
            , M_PatientRecordCPR prCPR, List<M_PatientRecordDiag> prDiag
            , List<M_PatientRecordECGImpressions> prECG
            , List<M_PatientRecordRescue> prRescue, List<M_PatientRecordMeasure> prMeasure
            , List<M_PatientRecordDrug> prDrug, List<M_PatientRecordSanitation> prSanitation
            , List<M_PatientRecordLossDrug> prLossDrug, List<M_PatientRecordLossSanitation> prLossSanitation)
        {
            using (var tran = db.Database.BeginTransaction())
            {
                try
                {
                    #region 修改病历主表
                    M_PatientRecord pInfo = (M_PatientRecord)info;

                    M_PatientRecord originInfo = dalContext.IM_PatientRecordDAL.GetModelWithOutTrace(a => a.PatientOrder == pInfo.PatientOrder && a.TaskCode == pInfo.TaskCode);

                    var entry = db.Entry(pInfo);
                    if (entry.State == EntityState.Detached)
                    {
                        //如果已经被上下文追踪
                        if (originInfo != null)
                        {
                            if (originInfo.SubmitLogo == false)
                            {
                                //originInfo = pInfo;//修改病历主表
                                pInfo.ForHelpTelephone = originInfo.ForHelpTelephone;
                                pInfo.OriginalTaskType = originInfo.OriginalTaskType;//原事件类型--不修改
                                pInfo.ForArea = originInfo.ForArea;
                                pInfo.AgentCode = originInfo.AgentCode;
                                pInfo.AgentWorkID = originInfo.AgentWorkID;//填写人工号
                                pInfo.AgentName = originInfo.AgentName;//填写人姓名
                                pInfo.BeginFillPatientTime = originInfo.BeginFillPatientTime;//开始填写病历时间
                                pInfo.MedicalRecordGenerationTime = originInfo.MedicalRecordGenerationTime;//病历生成时间
                                if (originInfo.FormCompleteLogo == true)
                                {
                                    pInfo.FormCompleteLogo = originInfo.FormCompleteLogo;//归档标识
                                    pInfo.FormCompleteTime = originInfo.FormCompleteTime;//归档时间
                                }
                                pInfo.ChargeOrder = originInfo.ChargeOrder;
                                if (originInfo.SubmitLogo == true)
                                {
                                    pInfo.SubmitLogo = originInfo.SubmitLogo;//提交标志
                                    pInfo.SubmitTime = originInfo.SubmitTime;//提交时间
                                    pInfo.MedicalStateCode = originInfo.MedicalStateCode;//不修改病历状态
                                }
                                pInfo.SubCenterIFSpotChecks = originInfo.SubCenterIFSpotChecks;//分中心是否抽查
                                pInfo.SubCenterPerson = originInfo.SubCenterPerson;
                                pInfo.SubCenterSpotChecksTime = originInfo.SubCenterSpotChecksTime;
                                pInfo.SubCenterSpotChecksResult = originInfo.SubCenterSpotChecksResult;
                                pInfo.SubCenterSpotChecksUnqualifiedReason = originInfo.SubCenterSpotChecksUnqualifiedReason;
                                pInfo.SubCenterSpotChecksRmark = originInfo.SubCenterSpotChecksRmark;
                                pInfo.CenterIFSpotChecks = originInfo.CenterIFSpotChecks;//中心是否抽查
                                pInfo.CenterSpotChecksPerson = originInfo.CenterSpotChecksPerson;
                                pInfo.CenterSpotChecksTime = originInfo.CenterSpotChecksTime;
                                pInfo.CenterSpotChecksResult = originInfo.CenterSpotChecksResult;
                                pInfo.CenterSpotChecksRmark = originInfo.CenterSpotChecksRmark;

                                pInfo.CenterSpotChecksUnqualifiedReason = originInfo.CenterSpotChecksUnqualifiedReason;
                                pInfo.IFNoticeAttendNursingLectures = originInfo.IFNoticeAttendNursingLectures;
                                pInfo.NoticeAttendTime = originInfo.NoticeAttendTime;
                                pInfo.NoticeAttendPerson = originInfo.NoticeAttendPerson;
                                pInfo.ActualAttendNursingLectures = originInfo.ActualAttendNursingLectures;
                                pInfo.ActualAttendTime = originInfo.ActualAttendTime;
                                pInfo.ActualAttendPerson = originInfo.ActualAttendPerson;
                                pInfo.IFFillNoticeAttendNursingLectures = originInfo.IFFillNoticeAttendNursingLectures;
                                pInfo.FillNoticeAttendTime = originInfo.FillNoticeAttendTime;
                                pInfo.FillNoticeAttendPerson = originInfo.FillNoticeAttendPerson;
                                pInfo.FillActualAttendNursingLectures = originInfo.FillActualAttendNursingLectures;
                                pInfo.FillActualAttendTime = originInfo.FillActualAttendTime;
                                pInfo.FillActualAttendPerson = originInfo.FillActualAttendPerson;
                                pInfo.IFMedicalHistoryWritingProgress = originInfo.IFMedicalHistoryWritingProgress;
                                pInfo.IFSubCenterMedicalHistoryWritingProgress = originInfo.IFSubCenterMedicalHistoryWritingProgress;
                                pInfo.IFFill2NoticeAttendNursingLectures = originInfo.IFFill2NoticeAttendNursingLectures;
                                pInfo.Fill2NoticeAttendTime = originInfo.Fill2NoticeAttendTime;
                                pInfo.Fill2NoticeAttendPerson = originInfo.Fill2NoticeAttendPerson;
                                pInfo.Fill2ActualAttendNursingLectures = originInfo.Fill2ActualAttendNursingLectures;
                                pInfo.Fill2ActualAttendTime = originInfo.Fill2ActualAttendTime;
                                pInfo.Fill2ActualAttendPerson = originInfo.Fill2ActualAttendPerson;

                                pInfo.CenterFollowUp = originInfo.CenterFollowUp;
                                pInfo.CenterFollowUpSupplement = originInfo.CenterFollowUpSupplement;
                                pInfo.UpdateFormCompletePerson = originInfo.UpdateFormCompletePerson;
                                pInfo.UpdateFormCompleteTime = originInfo.UpdateFormCompleteTime;

                                //pInfo.IMEI = originInfo.IMEI;

                                db.M_PatientRecord.Attach(pInfo);//将给定实体附加到集的基础上下文中，将实体以“未更改”的状态放置到上下文；
                                db.Entry(pInfo).State = EntityState.Modified;

                            }
                        }
                        //else//如果不在当前上下文追踪
                        //{
                        //    db.Entry(pInfo).State = EntityState.Modified;
                        //}

                    }
                    #endregion

                    #region 修改病历附表--体检等
                    M_PatientRecordAppend praInfo = dalContext.IM_PatientRecordAppendDAL.GetModelWithOutTrace(a => a.PatientOrder == pInfo.PatientOrder && a.TaskCode == pInfo.TaskCode);
                    if (praInfo != null && pra != null)
                    {
                        if (originInfo.SubmitLogo == false)
                        {
                            //pra.PhysicalExaminationSupplement = praInfo.PhysicalExaminationSupplement;//体检补充描述，应该没有，数据库应该删除
                            db.M_PatientRecordAppend.Attach(pra);//将给定实体附加到集的基础上下文中，将实体以“未更改”的状态放置到上下文；
                            db.Entry(pra).State = EntityState.Modified;//修改病历附表--体检等
                        }
                    }
                    else if (praInfo == null && pra != null)
                    {
                        db.M_PatientRecordAppend.Add(pra);//插入病历附表--体检等
                    }
                    #endregion

                    #region 修改病历附表--心肺复苏
                    M_PatientRecordCPR prCPRInfo = dalContext.IM_PatientRecordCPRDAL.GetModelWithOutTrace(a => a.PatientOrder == pInfo.PatientOrder && a.TaskCode == pInfo.TaskCode);
                    if (prCPRInfo != null && prCPR != null)
                    {
                        if (originInfo.SubmitLogo == false)
                        {
                            prCPR.EmergencyTime = prCPRInfo.EmergencyTime;//急救时长(页面没有显示，最后删除)
                            prCPR.ECGMonitoringTime = prCPRInfo.ECGMonitoringTime;//心电监护时间(页面没有显示，最后删除)
                            //prCPR.BeforeResuscitationECGDiagnosis = prCPRInfo.BeforeResuscitationECGDiagnosis;//20150916放开复苏前心电图诊断
                            prCPR.BeforeResuscitationSaO2 = prCPRInfo.BeforeResuscitationSaO2;
                            prCPR.IFLeaveHospital = prCPRInfo.IFLeaveHospital;//中心审核人员填写
                            prCPR.LeaveHospitalDate = prCPRInfo.LeaveHospitalDate;
                            prCPR.LeaveHospitalCPC = prCPRInfo.LeaveHospitalCPC;
                            prCPR.VerifyResults = prCPRInfo.VerifyResults;
                            prCPR.VerifyPerson = prCPRInfo.VerifyPerson;
                            prCPR.VerifyTime = prCPRInfo.VerifyTime;
                            prCPR.RegistrationPerson = prCPRInfo.RegistrationPerson;
                            prCPR.RegistrationTime = prCPRInfo.RegistrationTime;
                            prCPR.CenterIFAuditForXFFS = prCPRInfo.CenterIFAuditForXFFS;//中心审核心肺复苏
                            prCPR.CenterAuditPerson = prCPRInfo.CenterAuditPerson;
                            prCPR.CenterAuditTime = prCPRInfo.CenterAuditTime;
                            prCPR.CenterAuditResult = prCPRInfo.CenterAuditResult;
                            prCPR.CenterNotThroughReason = prCPRInfo.CenterNotThroughReason;
                            db.M_PatientRecordCPR.Attach(prCPR);//将给定实体附加到集的基础上下文中，将实体以“未更改”的状态放置到上下文；
                            db.Entry(prCPR).State = EntityState.Modified;//修改病历附表--心肺复苏
                        }
                    }
                    else if (prCPRInfo == null && prCPR != null)
                    {
                        db.M_PatientRecordCPR.Add(prCPR);//插入病历附表--心肺复苏
                    }
                    #endregion

                    #region 修改初步诊断子表
                    if (originInfo.SubmitLogo == false)
                    {
                        var dqry0 = from infos in db.M_PatientRecordDiag
                                    where infos.TaskCode == pInfo.TaskCode && infos.PatientOrder == pInfo.PatientOrder
                                    select infos;
                        foreach (var inf in dqry0)
                            db.M_PatientRecordDiag.Remove(inf);//删除初步诊断子表
                        //db.M_PatientRecordDiag.RemoveRange(prDiag);//删除初步诊断子表
                        if (prDiag != null)
                        {

                            db.M_PatientRecordDiag.AddRange(prDiag);//插入初步诊断子表
                        }
                    }
                    #endregion

                    #region 修改心电图印象子表
                    if (originInfo.SubmitLogo == false)
                    {
                        var dqry1 = from infos in db.M_PatientRecordECGImpressions
                                    where infos.TaskCode == pInfo.TaskCode && infos.PatientOrder == pInfo.PatientOrder
                                    select infos;
                        foreach (var inf in dqry1)
                            db.M_PatientRecordECGImpressions.Remove(inf);//删除心电图印象
                        //db.M_PatientRecordECGImpressions.RemoveRange(prECG);//删除心电图印象
                        if (prECG != null)
                        {

                            db.M_PatientRecordECGImpressions.AddRange(prECG);//插入心电图印象子表
                        }
                    }
                    #endregion

                    #region 修改救治记录主表
                    if (originInfo.SubmitLogo == false)
                    {
                        List<M_PatientRecordRescue> rescueList = dalContext.IM_PatientRecordRescueDAL.GetListBy(a => a.TaskCode == pInfo.TaskCode && a.PatientOrder == pInfo.PatientOrder);
                        db.M_PatientRecordRescue.RemoveRange(rescueList);//删除救治记录主表
                        if (prRescue != null)
                        {
                            db.M_PatientRecordRescue.AddRange(prRescue);//插入救治记录主表
                        }
                    }
                    #endregion

                    #region 修改救治措施子表
                    if (originInfo.SubmitLogo == false)
                    {
                        List<M_PatientRecordMeasure> prMeasureList = dalContext.IM_PatientRecordMeasureDAL.GetListBy(a => a.TaskCode == pInfo.TaskCode && a.PatientOrder == pInfo.PatientOrder);
                        db.M_PatientRecordMeasure.RemoveRange(prMeasureList);//删除救治措施子表
                        if (prMeasure != null)
                        {

                            db.M_PatientRecordMeasure.AddRange(prMeasure);//插入救治措施子表
                        }
                    }
                    #endregion

                    #region 修改药品子表
                    if (originInfo.SubmitLogo == false)
                    {
                        List<M_PatientRecordDrug> prDrugList = dalContext.IM_PatientRecordDrugDAL.GetListBy(a => a.TaskCode == pInfo.TaskCode && a.PatientOrder == pInfo.PatientOrder);
                        db.M_PatientRecordDrug.RemoveRange(prDrugList);//删除药品子表
                        if (prDrug != null)
                        {

                            db.M_PatientRecordDrug.AddRange(prDrug);//插入药品子表
                        }
                    }
                    #endregion

                    #region 修改耗材子表
                    if (originInfo.SubmitLogo == false)
                    {
                        List<M_PatientRecordSanitation> prSanitationList = dalContext.IM_PatientRecordSanitationDAL.GetListBy(a => a.TaskCode == pInfo.TaskCode && a.PatientOrder == pInfo.PatientOrder);
                        db.M_PatientRecordSanitation.RemoveRange(prSanitationList);//删除耗材子表
                        if (prSanitation != null)
                        {

                            db.M_PatientRecordSanitation.AddRange(prSanitation);//插入耗材子表
                        }
                    }
                    #endregion

                    #region 修改损耗药品子表
                    if (originInfo.SubmitLogo == false)
                    {
                        List<M_PatientRecordLossDrug> prLossDrugList = dalContext.IM_PatientRecordLossDrugDAL.GetListBy(a => a.TaskCode == pInfo.TaskCode && a.PatientOrder == pInfo.PatientOrder);
                        db.M_PatientRecordLossDrug.RemoveRange(prLossDrugList);//删除损耗药品子表
                        if (prLossDrug != null)
                        {

                            db.M_PatientRecordLossDrug.AddRange(prLossDrug);//插入损耗药品子表
                        }
                    }
                    #endregion

                    #region 修改损耗耗材子表
                    if (originInfo.SubmitLogo == false)
                    {
                        List<M_PatientRecordLossSanitation> prLossSanitationList = dalContext.IM_PatientRecordLossSanitationDAL.GetListBy(a => a.TaskCode == pInfo.TaskCode && a.PatientOrder == pInfo.PatientOrder);
                        db.M_PatientRecordLossSanitation.RemoveRange(prLossSanitationList);//删除损耗耗材子表
                        if (prLossSanitation != null)
                        {

                            db.M_PatientRecordLossSanitation.AddRange(prLossSanitation);//插入损耗耗材子表
                        }
                    }
                    #endregion

                    db.SaveChanges();//将在此上下文中所做的所有更改保存到基础数据库
                    tran.Commit(); //提交事务
                    return true;
                }
                catch (Exception ex)
                {
                    LogUtility.Error("MobileTaskDAL/Update(PAD)", ex.ToString());
                    if (tran != null)
                        tran.Rollback();  //回滚事务
                    return false;
                }
            }
        }
        #endregion

        #endregion


        #region PAD20160421更新发票号
        public bool UpdateFaPiaoNumber(string TaskCode, int PatientOrder, string FaPiaoNumber)
        {
            try
            {
                StringBuilder strSQL = new StringBuilder();
                strSQL.Append(@"update M_PatientCharge set InvoiceNumber='" + FaPiaoNumber + "' ");
                strSQL.Append(@" where TaskCode='" + TaskCode + "' and PatientOrder=" + PatientOrder + "  ");

                strSQL.Append(@"update M_PatientChargeLog set InvoiceNumber='" + FaPiaoNumber + "' ");
                strSQL.Append(@" where Isvalid=1 and TaskCode='" + TaskCode + "' and PatientOrder=" + PatientOrder + "  ");


                int ds = SqlHelper.ExecuteNonQuery(SqlHelper.MainConnectionString, CommandType.Text, strSQL.ToString(), null);
                return ds > 0 ? true : false;
            }
            catch (Exception ex)
            {
                LogUtility.Error("M_PatientRecordDAL/UpdateFollowUp()", ex.ToString());
                return false;
            }
        }
        #endregion

        #region 2016-12-13 zch 根据任务编码获取PatientOrder返回的是PatientMaxOrder 的值加1
        public int GetPatientOrderByTaskCode(string taskCode)
        {
            //return dalContext.IM_PatientRecordDAL.GetPatientMaxOrder(taskCode);

            M_PatientRecord pInfo = new M_PatientRecord();
            int PatientOrder = 0;
            var query = from pr in db.M_PatientRecord
                        where pr.TaskCode == taskCode
                        select pr.PatientOrder;
            if (query.Count() > 0)
                PatientOrder = query.Max();
            else
                PatientOrder = 0;
            return PatientOrder;
        }

        //2016-12-13 zch 根据任务编码和序号获取是否收费
        public int GetIFChargeByTaskCode(string taskCode, int PatientOrder)
        {
            M_PatientRecord pInfo = new M_PatientRecord();
            int IFCharge = 0;
            var query = from pr in db.M_PatientCharge
                        where pr.TaskCode == taskCode && pr.PatientOrder == PatientOrder
                        select pr.TaskCode;
            if (query.Count() > 0)
                IFCharge = 1;
            else
                IFCharge = 0;
            return IFCharge;
        }




        //2016-12-21 zch 根据userCode 获取只和任务相关内容
        public List<MobileTaskInfo> GetMobileTaskListPOCO(string userCode, string taskCode, ref string errorMsg)
        {
            try
            {
                SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(SqlHelper.MainConnectionString);//取管理库的链接字符串
                StringBuilder sbSQL = new StringBuilder();//sql语句
                sbSQL.Append("declare @taskCode char(22) ");
                sbSQL.Append("set @taskCode='" + taskCode + "' ");

                sbSQL.Append("declare @UserCode varchar(50) ");
                sbSQL.Append("set @UserCode=(select 编码 from TPerson where 工号='" + userCode + "') ");

                string sqlStr = @" select  distinct  top 10  
                                tt.任务编码,
                                tt.用户流水号,
                                case when pr.LocalAddress is null then ate.现场地址 else pr.LocalAddress end as '现场地址',
                                tt.到达现场时刻,tt.生成任务时刻,tae.首次受理时刻,
                                tt.出车时刻,tt.到达现场时刻,tt.离开现场时刻,tt.到达医院时刻,
                                tt.完成时刻,tt.返回站中时刻,
                                case when pr.[Name] is null then ate.患者姓名 else pr.Name end as '患者姓名',
                                tae.事件类型编码,    
								case when pr.PatientVersion is null then tzaet.名称  else pr.PatientVersion end as '事件类型',                               
                                司机=isnull(dbo.GetStr(tt.任务编码,3),''),                                
                                医生=isnull(dbo.GetStr(tt.任务编码,4),''),                              
                                护士=isnull(dbo.GetStr(tt.任务编码,5),''),
								case when pr.OriginalTaskType is null then tzaet.名称  else pr.OriginalTaskType end as '原事件类型', 
								case when pr.ContactTelephone is null then ate.联系电话  else pr.ContactTelephone end as '联系电话', 
								case when pr.ForArea is null then tae.区域  else pr.ForArea end as '区域'
								
		                        from TTask tt
		                        LEFT JOIN TAcceptEvent ate on ate.事件编码= tt.事件编码 and ate.受理序号=tt.受理序号
		                        LEFT JOIN TAlarmEvent tae on tae.事件编码= tt.事件编码
		                        LEFT JOIN TZAlarmEventType tzaet on tae.事件类型编码 = tzaet.编码
		                        LEFT JOIN dbo.TTaskPersonLink  tpl on tpl.任务编码=tt.任务编码 
                                 ";
                sbSQL.Append(sqlStr);

                sbSQL.Append(" left join ").Append(builder.InitialCatalog).Append(".dbo.M_PatientRecord  pr on pr.[TaskCode]=tt.任务编码");
                sbSQL.Append(" left join ").Append(builder.InitialCatalog).Append(".dbo.M_PatientCharge  pc on pc.[TaskCode]=tt.任务编码");
                sbSQL.Append(" where ");

                sbSQL.Append(" where ");

                string TaskCodeEnd = DateTime.Now.AddDays(-AppConfig.GetConfigInt("PADSelectTime")).ToString("yyyyMMddHHmmss") + "00000000";//PAD查询截止时间
                if (taskCode != "")
                {
                    sbSQL.Append("    tt.任务编码<@taskCode And");
                }
                sbSQL.Append(" (pr.SubmitLogo=0 or pr.SubmitLogo is null) And ");//20151216去掉已经提交的病历 
                sbSQL.Append(" tt.任务编码>'" + TaskCodeEnd + "' AND ");//20151213查询截止时间
                sbSQL.Append(" tpl.人员编码=@UserCode ");
                sbSQL.Append(" order by tt.任务编码 desc");

                DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.AttemperConnectionString, CommandType.Text, sbSQL.ToString(), null);
                List<MobileTaskInfo> list = new List<MobileTaskInfo>();
                if (ds.Tables[0].Rows.Count > 0)
                {
                    foreach (DataRow dr in ds.Tables[0].Rows)
                    {
                        MobileTaskInfo info = new MobileTaskInfo();
                        info.RenWuBianMa = dr["任务编码"].ToString();
                        info.YongHuLiuShuiHao = dr["用户流水号"].ToString();
                        info.XianChangDiZhi = dr["现场地址"].ToString();
                        info.DaoDaXianChangShiKe = dr["生成任务时刻"].ToString();
                        info.HuanZheXingMing = dr["患者姓名"].ToString();
                        info.EventType = dr["事件类型编码"].ToString();
                        info.EventTypeName = dr["事件类型"].ToString();
                        info.SiJi = dr["司机"].ToString();
                        info.YiSheng = dr["医生"].ToString();
                        info.HuShi = dr["护士"].ToString();
                        info.OriginalTaskType = dr["原事件类型"].ToString();//20151211
                        info.ForHelpTelephone = dr["联系电话"].ToString();//20151211
                        info.DrivingTime = dr["出车时刻"].ToString();//20151224
                        info.ArriveSceneTime = dr["到达现场时刻"].ToString();//20151224
                        info.LeaveSceneTime = dr["离开现场时刻"].ToString();//20151224
                        info.ArriveDestinationTime = dr["到达医院时刻"].ToString();//20151224
                        info.FirstAcceptTime = dr["首次受理时刻"].ToString();//20160107
                        list.Add(info);
                    }
                }

                return list;
            }
            catch (Exception ex)
            {
                List<MobileTaskInfo> listError = null;
                errorMsg = "系统错误：" + ex.Message;
                return listError;
            }
        }


//        //2016-12-21 zch 根据任务编码获取病历相关内容
//        public MobileTaskInfo GetMobilePRInfoPOCO(string taskCode, ref bool subMit)
//        {
//            StringBuilder sbSQL = new StringBuilder();//sql语句
//            sbSQL.Append("declare @taskCode char(22) ");
//            sbSQL.Append("set @taskCode='" + taskCode + "' ");


//            sbSQL.Append(@"
//
//                        select  top 1
//                        isnull(pr.LocalAddress,'') as '现场地址',
//                        isnull(pr.Name,'')  as '患者姓名',
//                        isnull(pr.PatientVersion,'')  as '事件类型',      
//                        isnull(pr.OriginalTaskType,'') as '原事件类型', 
//                         isnull(pr.ContactTelephone,'') as '联系电话', 
//                         isnull(pr.ForArea,'') as '区域'
//
//                        from [dbo].[M_PatientRecord] pr
//                        where pr.TaskCode =@taskcode   
//                        order by pr.PatientOrder   ");
//            return 
//        }

        /// <summary>
        /// 根据任务编码去病历中遍历是否提交字段,如果有未提交,就返回false
        /// 2016-12-22 zch 
        /// </summary>
        /// <param name="taskCode"></param>
        /// <returns></returns>
        public bool getMobilePRSubmit(string taskCode)
        {
            bool submit = true;
            var query = from pr in db.M_PatientRecord
                        where pr.TaskCode == taskCode
                        select pr.SubmitLogo;
            if (query != null)
                foreach (var sub in query)
                {
                    if (!(bool)sub)
                    { submit = false; }
                }
            return submit;

         
        }

        #endregion

        //2020-04-10 zch
        public int DeleteTaskImg(string taskCode, int typeCode, int PatientOrder)
        {
            StringBuilder sbSQL = new StringBuilder();//sql语句              
            sbSQL.Append(" DELETE M_PatientRecordIMG ");
            sbSQL.Append(" where  TaskCode ='" + taskCode + "' and TypeCode= " + typeCode + " and PatientOrder = " + PatientOrder + "");
            return SqlHelper.ExecuteNonQuery(SqlHelper.MainConnectionString, CommandType.Text, sbSQL.ToString(), null);

        }

        #region 移动支付 add2022-01-13 plq 从闵行移植

        #region 20200813 sr 支付订单信息新增以及修改操作
        //新增订单信息
        public void Insert(string danhao, string taskcode, int patientorder, string workcode, string paytype, double jine, DateTime generationtime, string endtime, bool ifrefund, int result, string remark, string callorder, string invoicenumber, string patientname, int cancelresult)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"insert into M_PatientPayRecord (订单号,任务编码,病历序号,人员工号,支付类型,交易金额,生成时间,结束时间,是否退款,交易结果,备注,用户流水号,发票号,病人姓名,撤销结果) values( ");
            sb.Append(" '" + danhao + "' ,");//订单号
            //sb.Append(" '" + tradeno + "' ,");//支付交易号
            sb.Append(" '" + taskcode + "' ,");//任务编码
            sb.Append(" '" + patientorder + "' ,");//病历序号
            sb.Append(" '" + workcode + "' ,");//人员工号
            //sb.Append(" '" + buyerid + "' ,");//付款账号
            sb.Append(" '" + paytype + "' ,");//支付类型
            sb.Append(" '" + jine + "' ,");//交易金额
            sb.Append(" '" + generationtime + "' ,");//生成时间
            sb.Append(" '" + endtime + "' ,");//结束时间
            //sb.Append(" '" + originaltradeno + "' ,");//退款原始单号
            sb.Append(" '" + ifrefund + "' ,");//是否退款
            sb.Append(" '" + result + "' ,");//交易结果
            sb.Append(" '" + remark + "' , ");//备注
            sb.Append(" '" + callorder + "' ,");//用户流水号
            sb.Append(" '" + invoicenumber + "' ,");//发票号
            sb.Append(" '" + patientname + "' , ");//病人姓名
            sb.Append(" '" + cancelresult + "') ");//撤销结果
            SqlHelper.ExecuteNonQuery(SqlHelper.MainConnectionString, CommandType.Text, sb.ToString(), null);
        }

        //更新M_PatientPayRecord表的交易结果字段
        public void Update(string outtradeno, int result, string endtime, string paytype)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(" update M_PatientPayRecord set 结束时间='" + endtime + "',交易结果='" + result + "',支付类型='" + paytype + "' where 订单号='" + outtradeno + "' ");
            //sb.Append(where 订单号=" + outtradeno + " );
            SqlHelper.ExecuteNonQuery(SqlHelper.MainConnectionString, CommandType.Text, sb.ToString(), null);
        }
        //更新撤销结果
        public void UpdateCancelResult(string outtradeno, int cancelresult, string endtime)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(" update M_PatientPayRecord set 是否退款='" + cancelresult + "'");
            sb.Append(" ,结束时间='" + endtime + "'");
            sb.Append(" where 订单号='" + outtradeno + "'");
            SqlHelper.ExecuteNonQuery(SqlHelper.MainConnectionString, CommandType.Text, sb.ToString(), null);
        }

        //新增退款记录
        public void InsetCancelResult(string outtradeno, string outrefundno, string work_code, string endtime)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("update M_PatientPayRecord set 是否退款=1 where 订单号='" + outtradeno + "' ");
            sb.Append(@" insert into M_PatientPayRecord  select 订单号='" + outrefundno + "',任务编码,病历序号,人员工号='" + work_code + "',支付类型,交易金额=-交易金额,生成时间,结束时间='" + endtime + "',是否退款,交易结果,备注,用户流水号='" + outtradeno + "',发票号,病人姓名,撤销结果 from M_PatientPayRecord where 订单号= '" + outtradeno + "' ;");
            SqlHelper.ExecuteNonQuery(SqlHelper.MainConnectionString, CommandType.Text, sb.ToString(), null);
        }

        public bool ISRefund(string outtradeno, ref string refundno)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("select top 1 * from M_PatientPayRecord where 用户流水号='" + outtradeno + "' and 交易结果=1 order by 订单号 desc ");
            using (SqlDataReader dr = SqlHelper.ExecuteReader(SqlHelper.MainConnectionString, CommandType.Text, sb.ToString(), null))
                try
                {
                    bool result = false;
                    if (dr.Read())
                    {
                        result = dr["是否退款"].ToString() == "True" ? true : false;
                        refundno = dr["订单号"].ToString();
                    }
                    return result;
                }
                catch (Exception ex)
                {
                    LogUtility.Error("MobileTaskDAL/UpdatePatientRecord", ex.Message);
                    return false;
                }
        }

        /// <summary>
        /// 获取订单号
        /// </summary>
        /// <param name="task_code"></param>
        /// <param name="patient_order"></param>
        /// <param name="outtradeno"></param>
        public void GetTradeNo(string task_code, int patient_order, out string outtradeno)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("select top 1 * from M_PatientPayRecord where 任务编码='" + task_code + "' and 病历序号=" + patient_order + " and 交易结果=2 order by 生成时间 desc ");
            using (SqlDataReader dr = SqlHelper.ExecuteReader(SqlHelper.MainConnectionString, CommandType.Text, sb.ToString(), null))
                try
                {
                    if (dr.Read())
                    {
                        outtradeno = dr["订单号"].ToString();
                    }
                    else
                    {
                        outtradeno = "";
                    }
                }
                catch (Exception ex)
                {
                    outtradeno = "";
                    LogUtility.Error("MobileTaskDAL/GetTradeNo", ex.Message);
                }
        }
        #endregion

        #endregion




        #region 获取医保诊断信息
        public void GetYBZdList(string taskCode, int patientOrder, string code, out List<M_ZICDNew> zdnos, out string result)
        {
            try
            {
                StringBuilder sbSQL = new StringBuilder();//sql语句
                sbSQL.Append(@"select ID,Name,PinYin,zdno,zdmc from M_ZICDNew where IsActive=1 and ID in (" + code + ") ");
                DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.MainConnectionString, CommandType.Text, sbSQL.ToString(), null);
                List<M_ZICDNew> list = new List<M_ZICDNew>();
                if (ds.Tables[0].Rows.Count > 0)
                {
                    foreach (DataRow dr in ds.Tables[0].Rows)
                    {
                        M_ZICDNew info = new M_ZICDNew();
                        info.ID = Convert.ToInt32(dr["ID"]);
                        info.Name = dr["Name"].ToString();
                        info.PinYin = dr["PinYin"].ToString();
                        info.zdno = dr["zdno"].ToString();
                        info.zdmc = dr["zdmc"].ToString();
                        list.Add(info);
                    }
                    result = "OK";
                    zdnos = list;
                }
                else
                {
                    result = "Null";
                    zdnos = list;
                }
            }
            catch (Exception ex)
            {
                LogUtility.Error("MobileTaskDAL/GetYBZdList", "程序异常：" + ex.Message);
                result = "Error";
                zdnos = null;
            }
        }
        #endregion



    }
}
